package com.ibm.cloud.envcheck.kit;

import java.io.IOException;
import java.io.InputStream;

import com.ibm.cloud.envcheck.bean.RemoteParam;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class RemoteExecService {
	private Channel channel;
	private InputStream in;
	private Session session;

	public RemoteExecService() {

	}

	public void handle(RemoteParam param) {
		initChannel(param);
		RemoteExecService.getOutputString(in, channel);
		destroy();
	}

	private void initChannel(RemoteParam param) {
		JSch jsch = new JSch();
		try {
			Session session = jsch.getSession(param.getUsername(), param.getHost(), param.getPort());
			UserInfo user = new RemoteUserInfor(param.getPassword());
			session.setUserInfo(user);
			session.connect();
			channel = session.openChannel("exec");
			((ChannelExec) channel).setCommand(param.getCommand());
			channel.setInputStream(null);
			//((ChannelExec) channel).setErrStream(System.err);
			in = channel.getInputStream();
			channel.connect();
		} catch (IOException e) {
			// log here
		} catch (JSchException e) {
			// log here
		}
	}

	public void init() {
	}

	public void destroy() {
		if((channel!=null)&&(!channel.isClosed())&&(channel.isConnected())){
			channel.disconnect();
		}
		if(session!=null && session.isConnected()){
			session.disconnect();
		}
	}

	public static void getOutputString(InputStream inputStream, Channel channel) {
		try {
			byte[] tmp = new byte[1024];
			while (true) {
				while (inputStream.available() > 0) {
					int i = inputStream.read(tmp, 0, 1024);
					if (i < 0)
						break;
					System.out.print(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {
					if (inputStream.available() > 0) {
						continue;
					}else{
						System.out.println("exit-status: " + channel.getExitStatus());
						inputStream.close();
						break;
					}
				}
				try {
					Thread.sleep(2000);
				} catch (Exception ee) {
				}
			}
		} catch (Exception e) {
			// log here
		}
	}

	private class RemoteUserInfor implements UserInfo {
		private String passwd;

		public RemoteUserInfor(String passwd) {
			this.passwd = passwd;
		}

		@Override
		public String getPassphrase() {

			return null;
		}

		@Override
		public String getPassword() {
			return passwd;
		}

		@Override
		public boolean promptPassphrase(String arg0) {

			return false;
		}

		@Override
		public boolean promptPassword(String arg0) {
			return true;
		}

		@Override
		public boolean promptYesNo(String arg0) {
			return true;
		}

		@Override
		public void showMessage(String arg0) {
		}

	}

}
